import axios from 'axios'
import { useUserStore } from '@/stores/index'
import { message } from 'ant-design-vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from "@/router"

axios.defaults.baseURL = import.meta.env.VITE_BASE_API

axios.defaults.timeout = 300000
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}

// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
  showSpinner: false
})

// HTTPrequest拦截
axios.interceptors.request.use(
  (config) => {
    NProgress.start() // start progress bar
    const userStore = useUserStore()
    let getToken = false
    if (config.headers && config.headers.getToken) {
      getToken = true
      delete config.headers.getToken
    }
    let token = userStore.access_token
    if (token && !getToken) {
      config.headers['token'] = token // token
    }

    // // headers中配置serialize为true开启序列化
    // if (config.method === 'post' && config.headers.serialize) {
    //   config.data = serialize(config.data)
    //   delete config.data.serialize
    // }

    // if (config.method === 'get') {
    //   config.paramsSerializer = function (params) {
    //     return qs.stringify(params, { arrayFormat: 'repeat' })
    //   }
    // }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    NProgress.done()
    if (res.status !== 200) {
        message.error("请求失败，请重试！")
        router.push({path: '/login'})
    } else {
      return res
    }
    return Promise.reject(res)
  },
  (error) => {
    NProgress.done()
    return Promise.reject(error)
  }
)

export default axios
